<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/*
 * Created on 2012-6-26
 *
 */
class MY_APP_Controller extends CI_Controller {
	public $accept = 'html';
	public $template;//模板文件
	public $assign = array();
	public $viewDir = "";
	public $curUser = null;
	public $configure = array();
	
	var $beforeFilter = array();
	
	public function __construct(){
		parent::__construct();
		$this->load->helper(array('form','url','system','language'));
		$this->lang->load('index');
		$this->lang->load('url');
		$this->load->library(array('session'));
		$this->accept = isset( $_GET['format'] ) ? strtolower( $_GET['format'] ) : 'html';
		if(isset($_GET['template'])){
			$this->template = $_GET['template'];
		}else{
			global $class,$method;
			$this->template = $class."/".$method;
		}
		$this->loadModule();
		if ($this->session->userdata('userId')) {
			$this->curUser = array(
				'id' => $this->session->userdata('userId'),
				'username' => $this->session->userdata('userName'),
				'truename' => $this->session->userdata('trueName'),
			);
		}
		$this->assign['_user'] = $this->curUser;
		$this->doBeforeFiter();
	}
	
	
	/**
	 * 加载数据库存储的系统配置信息(对应数据库的config表)
	 */
	protected function initConfig(){
		$cacheFile = realpath(APPPATH).'/tmp/~configure.php';
		if(file_exists($cacheFile)){
			$_configure = include($cacheFile);
		}else{
			$this->load->model('Config_model','Config');
			$rs = $this->Config->doList();
			foreach($rs as $_rs){
				$_configure[$_rs['code']] = $_rs['value'];
			}
			$content = 'return '.var_export( $_configure,true ).";\n";
			$content  = "<?php\n".$content."\n?>";
			fwritefile( $cacheFile,$content );
		}
		$sysCategoryTypes  = explode(',',$_configure['sys_category_types']);
		$_configure['sys_category_types'] = array();
		foreach($sysCategoryTypes as $key=>$val){
			$item = explode('=',$val);
			$_configure['sys_category_types'][$item[0]] = array(
				'id' => $item[0],
				'name' => $item[1],
			);
		}
		$this->configure = $_configure;
	}
	
	/**
	 * 执行前置过滤函数和方法
	 * except除了 都 执行
	 * only 都执行
	 * 
	 * var $beforeFilter = array(
			'initAdmin' => array(
				'only' => array('admin','add','remove','edit','save'),
			),
			'_init' => array(
				'only' => array('index','view','product','productview'),
			),
		);

	 */
	protected function doBeforeFiter(){
		if(empty($this->beforeFilter)){
			return;
		}
		global $method;
		$actionArray = array();
		foreach($this->beforeFilter as $action=>$setting){
			if(is_string($setting)){
				$actionArray[] = $setting;
			}else{
				if(isset($setting['except'])){
					if(!in_array($method,$setting['except'])){
						$actionArray[] = $action;
					}
					continue;
				}else if(isset($setting['only'])){
					if(in_array($method,$setting['only'])){
						$actionArray[] = $action;
					}
					continue;
				}else{
					$actionArray[] = $action;
				}
			}
		}
		if(!empty($actionArray)){
			foreach($actionArray as $action){
				$this->doRun($action);
			}
		}
	}
	
	/**
	 * 执行方法或者函数
	 * 
	 * @param string $action 方法或者函数名
	 * @param string $obj 方法所在的文件名
	 * @param array $param 传入的参数数组
	 */
	private function doRun($action,$obj=null,$param=array()){ 
		if(function_exists($action)){ 
			return call_user_func_array($action,$param); 
		}else{ 
			if($obj==null){ 
				 $obj = $this; 
			}elseif(is_string($obj)){ 
				include($obj); 
				$className = substr($obj,strrchr($obj,'.')); 
				$obj = new $className(); 
			} 
			 
			if( method_exists( $obj,$action ) ){ 
				return call_user_func_array(array($obj,$action),$param); 
			}else{ 
				show_error('MissAction '.get_class($obj).' '.$action  );
			} 
		} 
	}
	
	/**
	 * 验证的封装
	 */
/*	public function validation($rules,$model=null){
		$this->load->library('form_validation');
		$this->form_validation->set_rules($rules);
		if($model!=null){
			$fields = $model;
			if(is_string($model)){
				$this->lang->load('model');
				$fields = $this->lang->line("val_".$model);
			}
			$this->form_validation->set_fields($fields);
		}
		return $this->form_validation->run();
	}*/
	
	/**
	 * 加载系统模块
	 */
	protected function loadModule(){
		$result = format_tree($this->cacheModule());
		$modules = array();
		global $class,$method;
		foreach($result as $k=>$mo){
			if($mo['have_sub'] >0 ){
				$mo['sub'] = get_sub_tree($result,$mo['id']);
			}
			$modules[$k] = $mo;
			if($mo['mod_code'] == $class){//当前模块
				$this->assign['currModule'] = $mo;
			}
		}
		$this->assign['modules'] = $modules;
	}
	
	/**
	 * 缓存系统模块
	 */
	protected function cacheModule(){
		$result = array();
		$cacheFile = realpath(APPPATH).'/tmp/~sys_modules.php';
		if(file_exists($cacheFile)){
			$result = include($cacheFile);
		}else{
			$this->loadModel('module_model','module');
			$condition = array(
					//'where'=>array('status'=>1),
					'order'=>array('sorts'=>'DESC')
			);
			$result = $this->module->find($condition);
			$content = 'return '.var_export( $result,true ).";\n";
			$content  = "<?php\n".$content."\n?>";
			file_put_contents( $cacheFile,$content );
		}
		return $result;
	}
	
	/**
	 * where条件(搜索用)
	 */
	protected function _searchWhere($model) {
		$map	=	array();
        foreach($model->_field as $key=>$val) {
            if(isset($_GET[$key]) && $_GET[$key]!='' && $_GET[$key]!='-100') {
                $map[$key]	=	$_GET[$key];
            }
        }
        return $map;
    }

	/**
	 * like条件(搜索用)
	 */
	protected function _searchLike($model,$sfield=null,$keyword=null){	
		if(empty($sfield)){
			$sfield = isset($_GET['sfield'])?$_GET['sfield']:null;
		}
		if(empty($keyword)){
			$keyword = isset($_GET['keyword'])?$_GET['keyword']:null;
		}
		if(empty($sfield)||empty($keyword)) return null;
		if(is_string($sfield)) $sfield = explode(',',$sfield);
		$like = array();
		foreach($sfield as $f){
			if($f==$model->pk){
				$_REQUEST[$model->pk] = $keyword;
				continue;
			}
			$like[$f] = $keyword;
		}
		return $like;
	}
	
	/**
	 * @param Model $model 数据对象
	 * @param string $condition 查询条件 
	 * $condition = array(
	 * 	'where'=>array(),
	 * 	'order'=>array()
	 * )
	 */
	protected function getPager($model = null ,$condition = array()){
		$result = array();
		$order = $sort = false;
		if(isset($_GET['order'])){
			$order = $this->input->get('order');
		}else{
			$order = $model->pk;
		}
		if(isset($_GET['sort'])){
			$sort = $this->input->get('sort')=='asc'?'asc':'desc';
		}else{
			$sort = 'desc';
		}
		$condition['order'] = isset($condition['order'])?array_merge($condition['order'],array($order=>$sort)):array($order=>$sort);

		$count = $model->find($condition,true);
		if($count > 0){
			$this->load->library('pagination');
			$request = $this->security->xss_clean($_GET);
			//$request = $this->input->get(null,true);
			$config = $this->config->item('system_pager_cfg');
			if(isset($request['pagesize'])&&intval($request['pagesize'])>0){//动态设置pagesize
				$config['per_page'] = $request['pagesize'];
			}
			$condition['limit'] = $config['per_page'];//pagesize
			$condition['offset'] = isset($request['per_page'])?$request['per_page']:null;
			unset($request['per_page']);
			$config['page_query_string'] = true;
			$config['base_url'] = base_url().'/'.uri_string().'?'.http_build_query($request);
			//print_r(uri_string());exit;
			//$config['base_url'] = base_url().$_SERVER['REQUEST_URI']."?".http_build_query($request);
			//echo $config['base_url'];exit;
			//$config['use_page_numbers'] = TRUE;
			$config['total_rows'] = $count;
			$this->pagination->initialize($config);
			
			$result['pager'] = $this->pagination;
			$result['result'] = $model->find($condition);
		}
		return $result;
	}
	
	protected function showMessage($mesCode,$redirect=null){
		$div = "\n";
		$message = $this->lang->line($mesCode);
		if(empty($message)) $message = $mesCode;
		switch( $this->accept ){
			case 'html':
				$data['message'] = $message;
				$data['redirct'] = $redirect;
				$message_temp = $this->config->item('system_message_temp');
				include($message_temp);
				break;
			case 'json':
				$data['message'] = $message;
				$data['redirct'] = $redirect;
				print_r( json_encode( $data) );
				break;
			case 'js':
				$div = "[js]";
			default:
				$data['message'] = $message;
				$data['redirct'] = $redirect;
				echo implode( $div,$data );
				echo( $div ."\n" );
				break;
		}
		exit();
	}

	/**
	 * 加载模板
	 * @param string $template 文件名称
	 * @param array $data	传递的页面数据
	 */
	protected function display($template=null,$data=null){
		$template = empty($template)?$this->template : $template;
		if($this->accept!='html') $template = $this->accept."/".$template;
		$data = empty($data)? $this->assign : array_merge($this->assign,$data);
		$this->load->view($this->viewDir.$template,$data);
	}
	
	
	/**
     * 加载模型
	 *
     * @access protected 
     * @param string $name 数据对象名称 
     * @param string $aliasName 别名
     * @return void
     */
	protected function loadModel($model,$aliasName){
		$this->load->model($model,$aliasName);
		//如果没有字段就初始化
		if(empty($this->$aliasName->_field)){
			$this->$aliasName->init();
		}
	}
	
	public function index(){
		$this->display();
	}
	
}

/**
 * 后台父控制器
 */
class MY_ADMIN_Controller extends MY_APP_Controller{
	
	public function __construct(){
		parent::__construct();
		$this->viewDir = "admin/";
		global $class,$method;
		if($method !='login'){
			$this->initAdmin();
		}
	}
	
	/**
	 * 后台管理员权限验证
	 */
	protected function initAdmin(){
		$redirect = $_SERVER['REQUEST_URI'];
		$redirect = site_url('admin/users/login/?redirect='.urlencode($redirect));
		//如果成功登陆了
		if($this->authorize($redirect)){
			if(!empty($this->curUser['is_admin'])){
				if(intval($this->curUser['is_admin'])==1) return true;//超级管理员组
			}
			$this->showMessage('Permission denied',$redirect);
		}
	}
	
	protected function authorize($loginUrl=null){
		if($this->session->userdata('id') && $this->session->userdata('is_admin')){
			$this->curUser = array(
				'id' => $this->session->userdata('id'),
				'username' => $this->session->userdata('username'),
				'truename' => $this->session->userdata('username'),
				'is_admin' => $this->session->userdata('is_admin'),
			);
			$this->assign['_user'] = $this->curUser;
		}
		if($loginUrl==null) $loginUrl = $this->config->item('system_login_url');
		if(empty($this->curUser)){
			redirect($loginUrl, 'refresh');
		}
		return true;
	}
	
	public function editorUpload() {
		$CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents("js/ueditor/config.json")), true);
		$action = $_GET['action'];
		switch ($action) {
			case 'config':
				echo json_encode($CONFIG);
				break;
				/* 上传图片 */
			case 'uploadimage':
				return $this->ueditorUploadImages();
			default:
				echo json_encode(array(
				'state'=> '请求地址出错'
						));
						break;
		}
	}
	
	/**
	 * 上传封面图片
	 * @param int $fileId	唯一标识的ID
	 * @param string $type
	 * @param string $field
	 * @return multitype:boolean string NULL
	 */
	protected function uploadLogoFiles($fileId, $type='article', $field='logo') {
		$upPath = "data/images/logo/{$type}/";
		$config['allowed_types'] = 'gif|jpg|png';
		$config['max_size'] = '1024';
		//$config['encrypt_name'] = true;
		$config['overwrite'] = true;
		$config['file_name'] = $fileId;
		$config['remove_spaces'] = true;
		$result = array();
		if (empty($fileId)) {
			$config['upload_path'] = $upPath . date('Y-m-d-H') .'/';
		} else {
			$config['upload_path'] = $upPath.getUploadPath($fileId);
		}
		if (!is_dir($config['upload_path'])) {
			mkDirs($config['upload_path']);
		}
		$this->load->library('upload', $config);
		if ($this->upload->do_upload($field)){
			$upload = $this->upload->data();
			//缩略图
			$iconfig['source_image'] = $config['upload_path'] . $upload['raw_name'].$upload['file_ext'];
			$iconfig['new_image'] = $upload['raw_name'].$upload['file_ext'];
			$iconfig['width'] = 150;
			$iconfig['height'] = 150;
			$iconfig['maintain_ratio'] = true;
			$iconfig['create_thumb'] = true;
			$this->load->library('image_lib', $iconfig);
			$this->image_lib->resize();
			$result['result'] = true;
			$result['file'] = $config['upload_path'] . $upload['raw_name'].$upload['file_ext'];
		} else {
			$result['result'] = false;
			$result['error'] = $this->upload->display_errors();
		}
		return $result;
	}
	
	/**
	 * ueditor编辑器上传图片
	 * @param number $fileId
	 * @param string $type
	 */
	protected function ueditorUploadImages($fileId=0, $type='article') {
		$upPath = "data/images/ueditor/{$type}/";
		$config['allowed_types'] = 'gif|jpg|png';
		$config['max_size'] = '1024';
		$config['encrypt_name'] = true;
		$config['remove_spaces'] = true;
		$result = array();
		if (empty($fileId)) {
			$config['upload_path'] = $upPath . date('Y-m-d-H') .'/';
		} else {
			$config['upload_path'] = $upPath.getUploadPath($fileId);
		}
		if (!is_dir($config['upload_path'])) {
			mkDirs($config['upload_path']);
		}
		$this->load->library('upload', $config);
		if ($this->upload->do_upload('editUpFile')){
			$upload = $this->upload->data();
			$result['state'] = 'SUCCESS';
			$result['url'] = base_url($config['upload_path'] . $upload['raw_name'].$upload['file_ext']);
			$result['title'] = $upload['file_name'];
			$result['original'] = $upload['orig_name'];
			$result['type'] = $upload['image_type'];
			$result['size'] = $upload['file_size']/8000;
		} else {
			$result['state'] = $this->upload->display_errors();
		}
		echo json_encode($result);
	}
	
}
/* End of file MY_Controller.php */
/* Location: ./application/core/MY_Controller.php */